package com.enen.controller.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Date;
import java.util.Map;

@Data
@Configuration
public class JwtUtil {
//    私钥
    @Value("${jwt.config.key}")
    private  String key;
//    失效时间
    @Value("${jwt.config.ttl}")
    private Long ttl;


    /**
     * 设置认证token
     *
     */
    public String createJwt(String id, String name, Map<String,Object> map){
//        1、设置失效时间
        long now = System.currentTimeMillis();
        long exp = now+ttl;
//        2、创建JwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);

//        3、根据map设置claims
        for(Map.Entry<String,Object> entry:map.entrySet()){
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }

        jwtBuilder.setExpiration(new Date(exp));
//        4、创建token
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token字符串获取claims
     * @param token
     * @return
     */
    public Claims parseJwt(String token){
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims;
    }
}
